//
//  OrderPayForController.m
//  WuJieLive
//
//  Created by iMac on 2017/12/19.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "OrderPayForController.h"
#import "OrderPayForCell.h"
#import "OrderPayForHeaderView.h"
#import "PayMentsModel.h"
#import "PayForPasswordView.h"

@interface OrderPayForController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (nonatomic , strong) NSMutableArray * dataArray;

@property (nonatomic , strong) UIButton * currentBtn;

@property (nonatomic , assign) NSInteger index;

@property (nonatomic , strong) PayForPasswordView * payforView;

@end

@implementation OrderPayForController

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)leftBtnAction:(UIButton *)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)setNavi
{
    self.title = @"订单支付";
    
}

-(void)setUI
{
    self.index = -1;
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderPayForCell" bundle:nil] forCellReuseIdentifier:@"OrderPayForCell"];
    self.tableview.tableFooterView = [UIView new];
    OrderPayForHeaderView * headerView = [[[NSBundle mainBundle] loadNibNamed:@"OrderPayForHeaderView" owner:self options:nil] lastObject];
    headerView.frame = CGRectMake(0, 0, kScreenWidth, 130);
    NSString * string = [NSString stringWithFormat:@"¥%@",self.totalMonty];
    NSString * stringN = @"需支付:";
    NSString * tempString = [NSString stringWithFormat:@"%@%@",stringN,string];
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:tempString];
    [str setAttributes:@{NSForegroundColorAttributeName:MainColor,NSFontAttributeName:FontSize(18)} range:[tempString rangeOfString:string]];
    [str setAttributes:@{NSForegroundColorAttributeName:TextAssistColor,NSFontAttributeName:FontSize(13)} range:[tempString rangeOfString:stringN]];
    headerView.contentLabel.attributedText = str;
    self.tableview.tableHeaderView = headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderPayForCell * cell = [tableView dequeueReusableCellWithIdentifier:@"OrderPayForCell" forIndexPath:indexPath];
    PayMentsModel * model = self.dataArray[indexPath.row];
    cell.titleLabel.text = model.payment_name;
    if ([model.payment_name isEqualToString:@"余额"]) {
        cell.minorLabel.hidden = NO;
        cell.minorLabel.text = [NSString stringWithFormat:@"账户余额:%@",model.money];
        cell.iconImage.image = [UIImage imageNamed:@"icon_钱包支付"];
    }else if ([model.payment_name isEqualToString:@"小金库"]){
        cell.minorLabel.hidden = NO;
        cell.minorLabel.text = [NSString stringWithFormat:@"总金额:%@",model.money];
        cell.iconImage.image = [UIImage imageNamed:@"icon_user_小金库"];
    }else if ([model.payment_name isEqualToString:@"微信支付"]){
        cell.iconImage.image = [UIImage imageNamed:@"icon_微信支付_大"];
    }else if ([model.payment_name isEqualToString:@"支付宝"]){
        cell.iconImage.image = [UIImage imageNamed:@"icon_支付宝_大"];
    }else if ([model.payment_name containsString:@"银联"]){
        cell.iconImage.image = [UIImage imageNamed:@"icon_银联"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

-(void)setData
{
    self.dataArray = [NSMutableArray array];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken,@"order_ids":self.orderIDs,@"top_price":self.totalMonty,@"order_type":self.order_type};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/order-payment-way",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            for (int i = 0; i < [responseObject[@"data"][@"payments"] count]; i ++) {
                PayMentsModel * model = [PayMentsModel new];
                [model setValuesForKeysWithDictionary:responseObject[@"data"][@"payments"][i]];
                [self.dataArray addObject:model];
            }
            [self.tableview reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderPayForCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    self.index = indexPath.row;
    self.currentBtn.selected = NO;
    self.currentBtn = cell.rightBtn;
    self.currentBtn.selected = YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    UILabel * label = [[UILabel alloc]init];
    label.text = @"支付方式";
    label.textColor = TextLessImportColor;
    label.font = FontSize(13);
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.centerY.equalTo(view);
    }];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (IBAction)payForNow:(id)sender {
    if (self.index == -1) {
        [MBProgressHUD showError:@"请选择支付方式" toView:self.view];
        
    }else
    {
        __weak typeof(self) weakSelf = self;
        PayMentsModel * model = self.dataArray[self.index];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSDictionary * dict = @{@"token":self.userToken,@"order_ids":self.orderIDs,@"order_type":self.order_type,@"pay_code":model.payment_code};
        [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/order-pay",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (isSuccess) {
                if ([model.payment_name isEqualToString:@"余额"] || [model.payment_name isEqualToString:@"小金库"]) {
                    [weakSelf.view addSubview:weakSelf.payforView];
                    [weakSelf.payforView.tf showKeyboard];
                    weakSelf.payforView.tf.passwordDidChangeBlock = ^(NSString *password) {
                        if (password.length == 6 ) {
                            [weakSelf finalPayWithPassWord:password withID:responseObject[@"data"][@"merge_trade_id"]];
                        }
                    };
                }
                else {
                    [MBProgressHUD showError:@"支付宝微信银联没接" toView:self.view];
                }
                
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}

- (void)finalPayWithPassWord:(NSString *)password withID:(NSString *)mergeID
{
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken,@"merge_trade_id":mergeID,@"order_ids":self.orderIDs,@"order_type":self.order_type,@"pay_password":password};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/confer-pay-password",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            [weakSelf.payforView removeFromSuperview];
//            ResultController * vc = [[ResultController alloc]init];
//            [self.navigationController pushViewController:vc animated:YES];
            [MBProgressHUD showSuccess:@"支付成功" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            });
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

-(PayForPasswordView *)payforView
{
    if (!_payforView) {
        _payforView = [[[NSBundle mainBundle] loadNibNamed:@"PayForPasswordView" owner:self options:nil] lastObject];
        _payforView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }
    return _payforView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
